<template>
  <div>
    <div class="card-header">
      <px-radio-group v-model="className" @change="getChartData">
        <px-radio-button v-for="item in classNameList" :key="item.code" :label="item.code">{{ item.name }}</px-radio-button>
      </px-radio-group>
      <div class="flex items-center">
        <px-radio-group v-model="dateType" @change="getChartData">
          <px-radio-button label="day">天</px-radio-button>
          <px-radio-button label="week">周</px-radio-button>
          <px-radio-button label="month">月</px-radio-button>
          <px-radio-button label="year">年</px-radio-button>
          <px-radio-button label="other">自定义</px-radio-button>
        </px-radio-group>
        <px-date-picker
          v-if="dateType === 'other'"
          v-model="time"
          style="width: 280px"
          class="ml-[16px]"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="validateDateRange"
        />
      </div>
    </div>
    <div>
      <px-row style="width: 100%; margin: 0" :gutter="8">
        <px-col :span="7" style="padding-left: 0">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title flex items-center">
                  报警级别统计
                  <px-icon class="ml-[16px] pointer" @click="showAlarmDescription"><HelpCircle /></px-icon>
                </span>
                <px-tooltip content="下载" placement="top">
                  <px-button class="button" type="primary" link icon="Download" @click="handleDownload(levelRef)" />
                </px-tooltip>
              </div>
            </template>
            <PieCharts ref="levelRef" :className="className" :dateType="dateType" :chartsData="chartsData" :type="'level'" />
          </px-card>
        </px-col>
        <px-col :span="11">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">整体报警趋势</span>
                <px-tooltip content="下载" placement="top">
                  <px-button class="button" type="primary" link icon="Download" @click="handleDownload(seriesRef)" />
                </px-tooltip>
              </div>
            </template>
            <SeriesCharts ref="seriesRef" :className="className" :chartsData="chartsData" />
          </px-card>
        </px-col>
        <px-col :span="6" style="padding-right: 0">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">{{ leakType === "leak" ? "区域漏液侦测报警TOP10" : "报警区域TOP10" }}</span>
                <px-radio-group v-model="leakType" size="small" @change="getLeakChartData">
                  <px-radio-button label="area">区域</px-radio-button>
                  <px-radio-button label="leak">漏液</px-radio-button>
                </px-radio-group>
              </div>
            </template>
            <px-scrollbar>
              <px-table :data="leakTableData" class="equip-table" size="small" height="300" stripe>
                <px-table-column type="index" width="50" label="排名" align="center">
                  <template #default="scope">
                    <p v-if="scope.$index === 0" class="circle first">{{ scope.$index + 1 }}</p>
                    <p v-else-if="scope.$index === 1" class="circle second">{{ scope.$index + 1 }}</p>
                    <p v-else-if="scope.$index === 2" class="circle third">{{ scope.$index + 1 }}</p>
                    <p v-else>{{ scope.$index + 1 }}</p>
                  </template>
                </px-table-column>
                <px-table-column prop="positionName" label="区域名称" min-width="120" show-overflow-tooltip />
                <px-table-column v-if="leakType === 'leak'" prop="classNameDesc" label="所属科室" min-width="120" show-overflow-tooltip />
                <px-table-column #default="scope" label="报警数量" min-width="100" show-overflow-tooltip>
                  <px-button type="primary" link @click="handleArea(scope.row)">{{ scope.row.alarmNum }}</px-button>
                </px-table-column>
              </px-table>
            </px-scrollbar>
          </px-card>
        </px-col>
      </px-row>
      <px-row style="width: 100%; margin: 8px 0; box-sizing: border-box" :gutter="8">
        <px-col :span="7" style="padding-left: 0">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">报警类型占比</span>
                <px-tooltip content="下载" placement="top">
                  <px-button class="button" type="primary" link icon="Download" @click="handleDownload(pieRef)" />
                </px-tooltip>
              </div>
            </template>
            <PieCharts ref="pieRef" :className="className" :dateType="dateType" :chartsData="chartsData" />
          </px-card>
        </px-col>
        <px-col :span="11">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">报警时间趋势</span>
                <px-tooltip content="下载" placement="top">
                  <px-button class="button" type="primary" link icon="Download" @click="handleDownload(stackRef)" />
                </px-tooltip>
              </div>
            </template>
            <StackedLine ref="stackRef" :className="className" :chartsData="chartsData" />
          </px-card>
        </px-col>
        <px-col :span="6" style="padding-right: 0">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">系统报警TOP10</span>
              </div>
            </template>
            <px-scrollbar>
              <px-table :data="chartsData.systemAlarmDTOList || []" class="equip-table" size="small" height="300" stripe>
                <px-table-column type="index" width="50" align="center" label="排名">
                  <template #default="scope">
                    <p v-if="scope.$index === 0" class="circle first">{{ scope.$index + 1 }}</p>
                    <p v-else-if="scope.$index === 1" class="circle second">{{ scope.$index + 1 }}</p>
                    <p v-else-if="scope.$index === 2" class="circle third">{{ scope.$index + 1 }}</p>
                    <p v-else>{{ scope.$index + 1 }}</p>
                  </template>
                </px-table-column>
                <px-table-column prop="sysName" label="系统名称" min-width="200" show-overflow-tooltip />
                <px-table-column #default="scope" label="报警数量" min-width="120" show-overflow-tooltip>
                  <px-button type="primary" link @click="handleSystem(scope.row)">{{ scope.row.alarmNum }}</px-button>
                </px-table-column>
              </px-table>
            </px-scrollbar>
          </px-card>
        </px-col>
      </px-row>
      <px-row style="width: 100%">
        <px-col :span="24">
          <px-card shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">报警报表</span>
                <px-button class="button" type="primary" icon="Upload" @click="handleExport">导出</px-button>
              </div>
            </template>
            <CustomTabs class="mt-[-10px] ml-[16px]" :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
            <px-form
              v-if="activeName === 'system'"
              ref="formRef"
              class="custom-form-ui equip-form"
              :model="queryParams"
              inline
              label-position="right"
              label-width="80px"
            >
              <px-row :gutter="12">
                <px-col :span="8">
                  <EquipSystemTree
                    :facCode="queryParams.facCode"
                    :className="className"
                    :systemCode="queryParams.systemVal"
                    style="width: 100%"
                    @changeAllSystemCodes="changeAllSystemCodes"
                    @changeSystemCodes="changeSystemCodes"
                    @clearSystem="clearSystem"
                  />
                </px-col>
                <px-col :span="6">
                  <px-button type="primary" @click="getSystemAndAreaData">查询</px-button>
                  <px-button @click="resetTable">重置</px-button>
                </px-col>
              </px-row>
            </px-form>
            <px-scrollbar>
              <px-table :data="sysTableData" class="equip-table" size="small" border>
                <px-table-column type="index" label="序号" min-width="60" align="center" fixed="left" />
                <px-table-column v-for="(item, index) in tableColumns" :key="index" :label="item" show-overflow-tooltip>
                  <template #default="scope">{{ scope.row[item] === 0 ? scope.row[item] : scope.row[item] ? scope.row[item] : "-" }}</template>
                </px-table-column>
              </px-table>
            </px-scrollbar>
          </px-card>
        </px-col>
      </px-row>
    </div>
    <Detail v-model="dialogVisible" :class-name="className" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_ALERT_ANALYZE"
});

import { queryChartData, queryLeakChartData, querySystemChartData } from "@/api/alert";
import CustomTabs from "@/components/Tabs/index.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import Detail from "@/views/common/alert/rules/components/AlarmDescription/components/Detail.vue";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { computed, getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import PieCharts from "./components/PieCharts.vue";
import SeriesCharts from "./components/SeriesCharts.vue";
import StackedLine from "./components/StackedLine.vue";

const { proxy }: any = getCurrentInstance();

const levelRef = ref(""); // 报警级别统计
const pieRef = ref("");
const seriesRef = ref("");
const stackRef = ref("");
const time = ref([dayjs().subtract(1, "year").format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")]);
const dialogVisible = ref(false);

const state = reactive<any>({
  className: "MACHINE",
  dateType: "day",
  leakType: "area", // 区域漏液类型
  chartsData: {}, // 整体图表数据
  leakTableData: [], // 区域漏液列表
  sysTableData: [], // 系统报警列表
  tableColumns: [],
  tabList: [
    {
      name: "system",
      label: "系统"
    },
    {
      name: "area",
      label: "区域"
    }
  ],
  activeName: "system",
  queryParams: {},
  systemIdList: []
});
const { className, dateType, leakType, chartsData, leakTableData, sysTableData, tableColumns, tabList, activeName, queryParams, systemIdList } =
  toRefs(state);

const classNameList = JSON.parse(localStorage.getItem("classList"));
className.value = classNameList && classNameList[0]?.code;

const resetTable = () => {
  queryParams.value.systemVal = "";
  systemIdList.value = [];
  getSystemAndAreaData();
};

const params = computed(() => {
  if (dateType.value === "other") {
    return {
      className: className.value,
      dateType: dateType.value,
      systemVal: queryParams.value.systemVal,
      startTime: time.value[0],
      endTime: time.value[1]
    };
  }
  return {
    className: className.value,
    dateType: dateType.value,
    systemVal: queryParams.value.systemVal
  };
});

const paramsForLeak = computed(() => {
  if (dateType.value === "other") {
    return {
      className: className.value,
      dateType: dateType.value,
      isLeak: leakType.value === "leak" ? true : false,
      startTime: time.value[0],
      endTime: time.value[1]
    };
  }
  return {
    className: className.value,
    dateType: dateType.value,
    isLeak: leakType.value === "leak" ? true : false
  };
});

const handelTabSelected = selectName => {
  activeName.value = selectName;
  getSystemAndAreaData();
};

// 校验日期范围是否超过1年
const validateDateRange = val => {
  if (val && val.length === 2) {
    let [start, end] = val;
    start = new Date(start).getTime();
    end = new Date(end).getTime();
    const diffInMs = end - start;
    const oneYearInMs = 365 * 24 * 60 * 60 * 1000; // 1年的毫秒数（不考虑闰年）
    if (diffInMs > oneYearInMs) {
      PxMessage.error("时间间隔不能超过1年！");
      time.value = [dayjs(start).format("YYYY-MM-DD"), dayjs(start + oneYearInMs).format("YYYY-MM-DD")];
    }
    getChartData();
  }
};

const showAlarmDescription = () => {
  dialogVisible.value = true;
};

const getLeakChartData = async () => {
  leakTableData.value = await queryLeakChartData(paramsForLeak.value);
};

const getChartData = async () => {
  chartsData.value = await queryChartData(params.value);
  getSystemAndAreaData();
  getLeakChartData();
};

// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemVal = val;
  systemIdList.value = val2;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.facCode = val;
  queryParams.value.className = val2;
  queryParams.value.systemVal = val3;
  systemIdList.value = val4;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemVal = "";
  systemIdList.value = [];
};

const router = useRouter();
const handleSystem = row => {
  const { startTime, endTime } = chartsData.value;
  router.push(`/all/alert/business?systemCode=${row.sysCode}&className=${className.value}&active=ALL&startTime=${startTime}&endTime=${endTime}`);
};
const handleArea = row => {
  const { startTime, endTime } = chartsData.value;
  router.push(
    `/all/alert/business?positionCode=${row.positionCode}&className=${leakType.value === "leak" ? row.className : className.value}&active=ALL&startTime=${startTime}&endTime=${endTime}`
  );
};
const getSystemAndAreaData = async () => {
  const data = {
    ...params.value,
    isArea: activeName.value === "system" ? false : true
  };
  const res: any = await querySystemChartData(data);
  tableColumns.value = res.headList;
  sysTableData.value = res.dataList;
};

onMounted(() => {
  getChartData();
});

// 系统报警列表
const handleExport = () => {
  const data = {
    ...params.value,
    isArea: activeName.value === "system" ? false : true
  };
  const fileName = activeName.value === "system" ? "系统报警列表.xlsx" : "区域报警列表.xlsx";
  proxy.download("post", "/sharing/api/v1/alarm/systemAlarmExport", data, fileName);
};

const handleDownload = ref => {
  console.log(ref);
  ref.downLoad();
};
</script>

<style lang="scss" scoped>
:deep(.px-card__header) {
  border: none;
}

:deep(.px-card__body) {
  padding: 0 15px !important;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.circle {
  width: 16px;
  height: 16px;
  margin: 0 auto;
  line-height: 16px;
  color: #fff;
  text-align: center;
  border-radius: 50%;
}

.first {
  background-color: #ef4444;
}

.second {
  background-color: #ff771e;
}

.third {
  background-color: #f59e0b;
}

.card-title {
  width: 280px;
  height: 32px;
  padding-left: 8px;
  border-left: 3px solid #3b82f6;
  background-image: linear-gradient(to right, rgb(59, 130, 246), #fff);
  background: linear-gradient(270deg, rgba(59, 130, 246, 0) 0%, rgba(59, 130, 246, 0.24) 100%);
  font-size: 18px;
  font-family:
    PingFangSC-Medium,
    PingFang SC;
  font-weight: 500;
  color: #000000;
  line-height: 32px;
  // position: relative;
  // margin-left: 10px;

  // &::before {
  //   position: absolute;
  //   top: 50%;
  //   left: -10px;
  //   display: block;
  //   width: 3px;
  //   height: 16px;
  //   content: "";
  //   background: #3b82f6;
  //   border-radius: 0 100px 100px 0;
  //   transform: translateY(-50%);
  // }
}
</style>
